package cn.pconline.autoclub.web.admin;

import cn.pconline.autoclub.entity.ClubIntegral;
import cn.pconline.autoclub.entity.ClubMember;
import cn.pconline.autoclub.entity.MemberPetrolLog;
import cn.pconline.autoclub.entity.UserLimit;
import cn.pconline.autoclub.service.MemberService;
import cn.pconline.autoclub.service.PetrolService;
import cn.pconline.autoclub.service.UserLimitService;
import cn.pconline.autoclub.util.Pager;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.http.impl.cookie.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.gelivable.web.Env;
import org.gelivable.web.EnvUtils;
import org.gelivable.webmvc.JSONBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 *
 * @author wanganning
 */
@Controller
@RequestMapping("/admin")
public class PetrolLogController {

    @Autowired
    private PetrolService petrolService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private UserLimitService userLimitService;
    
    private static final Logger log = LoggerFactory.getLogger(AdminUserController.class);
    /**
     * 用户积分日志查询
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/petrol/list")
    public String queryAllLog(HttpServletRequest request, HttpServletResponse response) {
        Env env = EnvUtils.getEnv();
        String clubName = env.param("clubName", "");
        long clubId = env.paramLong("clubId", 0l);
        String username = env.param("username", "");
        String reason = env.param("reason", "");
        int pageNo = env.paramInt(("pageNum"), 1);
        int pageSize = env.paramInt(("pageSize"), 20);
        String startStr = request.getParameter("start");
        String endStr = request.getParameter("end");
        Date start = env.parseDate(StringUtils.defaultIfBlank(startStr, "1970-01-01 00:00:00"));
        Date end = env.parseDate(StringUtils.defaultIfBlank(endStr, "2970-01-01 00:00:00"));
        if (StringUtils.isNotBlank(startStr) && StringUtils.isNotBlank(endStr)
                && ((start.getMonth() != end.getMonth()) || (start.getYear() != end.getYear()))) {
            request.setAttribute("msg", "日期不能跨月");
        }
        Pager<MemberPetrolLog> pager = petrolService.queryLog(clubName, clubId, username, start, end, reason, pageNo, pageSize);
        List<ClubIntegral> reasons = petrolService.getIntegralsForUserLog();
        request.setAttribute("reasons", reasons);
        request.setAttribute("list", pager.getResultList());
        request.setAttribute("clubName", clubName);
        request.setAttribute("clubId", clubId);
        request.setAttribute("username", username);
        request.setAttribute("reason", reason);
        request.setAttribute("start", startStr);
        request.setAttribute("end", endStr);
        request.setAttribute("reason", reason);
        request.setAttribute("total", pager.getTotal());
        request.setAttribute("pageNum", pager.getPageNo());
        request.setAttribute("pageSize", pager.getPageSize());
        return "/admin/petrol/list";
    }

    /**
     * 导出用户积分日志
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/petrol/petrolLogBatchExport")
    public void petrolLogBatchExport(HttpServletRequest request, HttpServletResponse response) {
        Env env = EnvUtils.getEnv();
        String clubName = env.param("clubName", "");
        long clubId = env.paramLong("clubId", 0l);
        String username = env.param("username", "");
        String reason = env.param("reason", "");
        int pageNo = env.paramInt(("pageNum"), 1);
        int pageSize = env.paramInt(("pageSize"), 1000);
        String startStr = request.getParameter("start");
        String endStr = request.getParameter("end");
        Date start = env.parseDate(StringUtils.defaultIfBlank(startStr, "1970-01-01 00:00:00"));
        Date end = env.parseDate(StringUtils.defaultIfBlank(endStr, "2970-01-01 00:00:00"));
        if (StringUtils.isNotBlank(startStr) && StringUtils.isNotBlank(endStr)
                && ((start.getMonth() != end.getMonth()) || (start.getYear() != end.getYear()))) {
            request.setAttribute("msg", "日期不能跨月");
        }
        Pager<MemberPetrolLog> pager = petrolService.queryLog(clubName, clubId, username, start, end, reason, pageNo, pageSize);
        /**
         * 生成excel文件
         */
        String[] cellString = new String[]{"车友会ID", "车友会名称", "个性域名", "用户名", "油值", "积分类型", "时间"};
        HSSFWorkbook work = new HSSFWorkbook();
        HSSFSheet sheet = work.createSheet("用户积分日志表");
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < cellString.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(cellString[i]);
        }
        /**
         * 根据分页数据生成excel文件
         */
        if (pager.getResultList() != null) {
            for (int curPage = pageNo; curPage <= pager.getPageCount(); curPage++) {
                // 数据一页一页加载
                if (curPage != pageNo) {
                    pager = petrolService.queryLog(clubName, clubId, username, start, end, reason, curPage, pageSize);
                }
                //petrol
                for (int i = 0; i < pager.getResultList().size(); i++) {
                    
                    MemberPetrolLog log = pager.getResultList().get(i);
                    HSSFRow rowData = sheet.createRow(((curPage - 1) * pageSize) + i + 1);
                    rowData.createCell(0).setCellValue(log.getClubId());
                    rowData.createCell(1).setCellValue(log.getClub().getName());
                    rowData.createCell(2).setCellValue(log.getClub().getClubUrl());
                    rowData.createCell(3).setCellValue(log.getUser().getUsername());
                    rowData.createCell(4).setCellValue(log.getPetrol());
                    rowData.createCell(5).setCellValue(log.getReason());
                    rowData.createCell(6).setCellValue(DateUtils.formatDate(log.getCreateAt(), "yyyy-MM-dd HH:mm:ss"));
                }
            }
        }
        try {
            //设置返回数据类型
            response.setContentType("application/vnd.ms-excel;charset=GBK");
            //设置返回的文件名
            response.setHeader("Content-Disposition",
                    "attachment;Filename=userPetrolLog.xls");
            OutputStream out = response.getOutputStream();
            work.write(out);
            out.flush();
            out.close();
        } catch (IOException ex) {
        	log.error("listBatchExport fail!", ex);
        }
    }
    
    /**
     * 用户总油值查询
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/petrol/detail")
    public String queryMemberDetail(HttpServletRequest request, HttpServletResponse response) {
        Env env = EnvUtils.getEnv();
        String clubName = env.param("clubName", "");
        String username = env.param("username", "");
        int pageNum = env.paramInt(("pageNum"), 1);
        int pageSize = env.paramInt(("pageSize"), 20);
        Pager<ClubMember> pager = memberService.getClubMemberPage(clubName, username, pageNum, pageSize);
        request.setAttribute("list", pager.getResultList());
        request.setAttribute("clubName", clubName);
        request.setAttribute("username", username);
        request.setAttribute("total", pager.getTotal());
        request.setAttribute("pageNum", pager.getPageNo());
        request.setAttribute("pageSize", pager.getPageSize());
//        callback(response, 200, "修改成功", "petrol-detail", null);
        return "/admin/petrol/detail";
    }
    
    /**
     * 导出用户总油值
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/petrol/userPetrolBatchExport")
    public void userPetrolBatchExport(HttpServletRequest request, HttpServletResponse response) {
        Env env = EnvUtils.getEnv();
        String clubName = env.param("clubName", "");
        String username = env.param("username", "");
        int pageNo = env.paramInt("pageNum", 1);
        int pageSize = env.paramInt("pageSize", 1000);

        Pager<ClubMember> pager = memberService.getClubMemberPage(clubName, username, pageNo, pageSize);
        /**
         * 生成excel文件
         */
        String[] cellString = new String[]{"车友会ID", "车友会名称", "个性域名", "用户ID", "用户名", "油值"};
        HSSFWorkbook work = new HSSFWorkbook();
        HSSFSheet sheet = work.createSheet("用户总油值表");
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < cellString.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(cellString[i]);
        }
        /**
         * 根据分页数据生成excel文件
         */
        if (pager.getResultList() != null) {
            for (int curPage = pageNo; curPage <= pager.getPageCount(); curPage++) {
                // 数据一页一页加载
                if (curPage != pageNo) {
                    pager = memberService.getClubMemberPage(clubName, username, curPage, pageSize);
                }
                //petrol
                for (int i = 0; i < pager.getResultList().size(); i++) {
                    
                    ClubMember clubMember = pager.getResultList().get(i);
                    HSSFRow rowData = sheet.createRow(((curPage - 1) * pageSize) + i + 1);
                    rowData.createCell(0).setCellValue(clubMember.getClubId());
                    rowData.createCell(1).setCellValue(clubMember.getClub().getName());
                    rowData.createCell(2).setCellValue(clubMember.getClub().getClubUrl());
                    rowData.createCell(3).setCellValue(clubMember.getUser().getUid());
                    rowData.createCell(4).setCellValue(clubMember.getUser().getUsername());
                    rowData.createCell(5).setCellValue(clubMember.getPetrol());
                }
            }
        }
        try {
            //设置返回数据类型
            response.setContentType("application/vnd.ms-excel;charset=GBK");
            //设置返回的文件名
            response.setHeader("Content-Disposition",
                    "attachment;Filename=userPetrol.xls");
            OutputStream out = response.getOutputStream();
            work.write(out);
            out.flush();
            out.close();
        } catch (IOException ex) {
        	log.error("listBatchExport fail!", ex);
        }
    }
    

    /**
     * 用户预警查询
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/petrol/listWarnUser")
    public String listWarnUser(HttpServletRequest request, HttpServletResponse response) {
        Env env = EnvUtils.getEnv();
        String beginDate = env.param("beginDate", "");
        String endDate = env.param("endDate", "");
        int pageNum = env.paramInt("pageNum", 1);
        int pageSize = env.paramInt("pageSize", 20);
        Pager<UserLimit> pager = userLimitService.getUserLimitByDate(beginDate, endDate, UserLimit.DAILY_PERSON_LIMIT, pageNum, pageSize);
        request.setAttribute("pager", pager);
        request.setAttribute("beginDate", beginDate);
        request.setAttribute("endDate", endDate);
        return "/admin/petrol/listWarnUser";
    }

    /**
     * 返回语句块(适用于Geli2.0)
     *
     * @param resp
     * @param statusCode - 返回状态代码，200=成功，300=失败
     * @param message - 操作后的提示内容
     * @param navTabId - 返回的navTabId
     * @param callbackType - 回调方式，例如closeCurrent
     * @return
     */
    public String callback(HttpServletResponse resp, int statusCode, String message, String navTabId, String callbackType) {
        JSONBuilder json = new JSONBuilder();
        resp.setCharacterEncoding("UTF-8");
        if (statusCode > 0) {
            json.put("statusCode", statusCode);
        }
        if (StringUtils.isNotBlank(message)) {
            json.put("message", message);
        }
        if (StringUtils.isNotBlank(navTabId)) {
            json.put("navTabId", navTabId);
        }
        if (StringUtils.isNotBlank(callbackType)) {
            json.put("callbackType", callbackType);
        }
        try {
            resp.getWriter().println(json.toString());
        } catch (IOException ex) {
            //system error.
        }
        return null;
    }
}
